package Audio
{
	import Config.GameConfig;
	
	import Easing.Linear;
	
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;

	public class GameSoundChannel
	{
		public var sc:SoundChannel;
		public var ss:SoundScene;
		public var removed:Boolean=false;
		private var time:int=0;
		public var waitStop:Boolean=false;
		public var lastVolume:Number=-1;
		public var sound:GameSound;
		public var length:int=0;
		public function GameSoundChannel()
		{
			super();
		}
		public function update():void
		{
			var volume:Number=getVolume();
			if(sound.fadeInDuration>0)
			{
				time++;
				if(time<=sound.fadeInDuration)
				{
					volume=Linear.ease(time,0,volume-0,sound.fadeInDuration);
				}
			}
			if(waitStop)
			{
				time++;
				if(time<=sound.fadeOutDuration)
				{
					volume=Linear.ease(time,volume,0-volume,sound.fadeOutDuration);
				}
				else
				{
					remove();
				}
			}
			if(lastVolume!=volume)
			{
				lastVolume=volume;
				var transform:SoundTransform=sc.soundTransform;
				transform.volume=volume;
				sc.soundTransform=transform;
			}
			if(sc.position==length)
			{
				if(!sound.isMusic)
				{
					remove();
				}
			}
		}
		public function getVolume():Number
		{
			var volume:Number=sound.volume;
			if(sound.isMusic)
			{
				volume=GameConfig.musicVolume*volume;
				if(GameConfig.musicMute)
				{
					volume=0;
				}
			}
			else
			{
				volume=GameConfig.soundVolume*volume;
				if(GameConfig.soundMute)
				{
					volume=0;
				}
			}
			return volume;
		}
		public function stop():void
		{
			if(sound.fadeOutDuration>0)
			{
				time=0;
				waitStop=true;
			}
			else
			{
				remove();
			}
		}
		public function remove():void
		{
			sc.stop();
			ss.toSyncRemoved=true;
			removed=true;
		}
	}
}